<template>
  <div class="StudentTaskTable-Panel">
    <div class="StudentTaskTable-Panel-title">
      <div>
        <img src="@/assets/img/other/icon-学生列表.png" />
      </div>
      <div>
        <span>任务列表</span>
      </div>
    </div>
    <div class="StudentTaskTable-Panel-table" v-loading="State.TabLoading"
      element-loading-background="rgba(255, 255, 255, 0.6)">
      <el-table :data="State.StudentallInformation" style="width: 98%" height="98%" v-table-infinite-scroll="Load"
        :default-sort="{ prop: 'date', order: 'ascending' }">
        <el-table-column prop="taskName" label="任务名称" min-width="22.3%" sortable>
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ scope.row.taskName }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="creationTime" label="创建时间" min-width="22.3%" sortable>
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ dateFormats(scope.row.creationTime) }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="得分" min-width="20%" sortable>
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ scope.row.score }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="useTime" label="用时" min-width="20%" sortable>
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ TimeChange(scope.row.useTime) }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="option" label="操作" min-width="31.4%">
          <template #default="scope">
            <el-button class="StudentTaskTable-template-stare"
              v-if="scope.row.completeState === 0 || scope.row.completeState === 1"
              @click="StudentOpenTask(scope.row, scope.$index)">开始任务</el-button>
            <el-button class="StudentTaskTable-template-studentall" v-if="scope.row.completeState === 2"
              @click="handleResult(scope.row, scope.$index)">成绩详情</el-button>
            <!-- <el-button class="StudentTaskTable-template-Notinvolved" v-if="scope.row.completeState === 1">进行中
            </el-button> -->
            <el-button class="StudentTaskTable-template-Notinvolved" v-if="scope.row.completeState === 3">未参与
            </el-button>
            <!-- <el-button class="StudentTaskTable-template-Notinvolved" v-if="scope.row.completeState === 2 || scope.row.completeState === 3" >已结束
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div class="StudentTaskTable-el-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="StudentTaskPage.currentPage"
          :page-sizes="[5,10,20,30]" 
          :page-size="StudentTaskPage.pagesize"        
          layout="total, sizes, prev, pager, next, jumper"
          :total="State.StudentallInformation.length">    
        </el-pagination>
      </div> -->
  </div>
</template>

<script>
import { defineComponent, reactive, toRef, toRefs, watch, ref } from "vue";
import { postData, dateFormats, TimeChange } from "@/assets/js/pubilcs.js";
import router from '@/router'
import HomeContent from "../HomeContent";
import bus from "@/bus.js";
import { ElMessage } from 'element-plus'
export default defineComponent({
  name: "StudentTasksTable",
  components: {},
  props: {
    StudentallInformation: {
      type: Array,
      default: "",
    },
  },
  setup(props, ctx) {
    let State = reactive({
      StudentallInformation: [],
      AllStudentallInformation: [],
      TabLoading: true,
    });
    let InfiniteScrollCount = ref(15)
    //监听父组件传过来的比赛详情的值
    watch(() => props.StudentallInformation, (val, old) => {
      // State.StudentallInformation = val;
      State.TabLoading = false
      State.StudentallInformation = []
      State.AllStudentallInformation = ExchangeData(val)
      if (State.AllStudentallInformation.length > InfiniteScrollCount.value) {
        for (let i = 0; i < InfiniteScrollCount.value; i++) {
          State.StudentallInformation.push(State.AllStudentallInformation[i])
        }
      } else {
        for (let i = 0; i < State.AllStudentallInformation.length; i++) {
          State.StudentallInformation.push(State.AllStudentallInformation[i])
        }
      }
    },
      { deep: true }
    );
    //位置互换函数
    function ExchangeData(data) {
      console.log('data', data);
      let arr = []
      for (let i = data.length - 1; i >= 0; i--) {
        arr.push(data[i])
      }
      return arr
    }
    function Load() {
      InfiniteScrollCount.value += 7
      if (InfiniteScrollCount.value > State.AllStudentallInformation.length) {
        let count = Math.abs(State.AllStudentallInformation.length - InfiniteScrollCount.value)
        for (let i = InfiniteScrollCount.value - 7; i < InfiniteScrollCount.value - count; i++) {
          State.StudentallInformation.push(State.AllStudentallInformation[i])
        }
      } else {
        for (let i = InfiniteScrollCount.value - 7; i < InfiniteScrollCount.value; i++) {
          State.StudentallInformation.push(State.AllStudentallInformation[i])
        }
      }
      // console.log("滚动到底了")
    }
    //分页数据
    let StudentTaskPage = reactive({
      currentPage: 1,
      pagesize: 10,
    })
    function handleResult(row, index) {
      console.log('学生成绩详情');
      
      console.log('成绩详情----------', sessionStorage.getItem('ModelType'));
      console.log('row.trainingResultId', row.trainingResultId);

      postData("/api/TrainingResult/GetById", JSON.stringify({ Id: row.trainingResultId }), sessionStorage.getItem("token")).
        then(function (res) {
          console.log('------------------', res);
          // HomeContent.Default.taskName.value = res.result.result.trainingTaskName
          // HomeContent.Default.player.value = res.result.result.userName

          if (res.result.result.orders == '') {
            HomeContent.Default.operateRecord.value = JSON.parse(res.result.result.record)
          } else {
            HomeContent.Default.AED.value = JSON.parse(res.result.result.orders)
            console.log('111');
            if (JSON.parse(res.result.result.orders).Record) {
              console.log('获取的成绩详情', JSON.parse(res.result.result.orders));
              HomeContent.Default.ratingForm.value = JSON.parse(res.result.result.orders).Record.RatingForm.RatingForm;
              console.log('222');

              HomeContent.Default.Synthetical.value = JSON.parse(res.result.result.orders).Record.Synthetical
              console.log('333');

              HomeContent.Default.FaultRepair.value = JSON.parse(res.result.result.orders).Record.FaultRepair;
              console.log('444');

              HomeContent.Default.workOrderSheet.value = JSON.parse(res.result.result.orders).Record.WorkOrderSheet;
              console.log('HomeContent.Default.Synthetical.value', HomeContent.Default.Synthetical.value);
            }
          }




          if (res.result.success) {
            if (sessionStorage.getItem('ModelType') == 999) {
              ElMessage({
                message: '暂无数据！',
                type: 'warning',
              })
            } else {  // ===============
              // if (res.result.result.record == null) {
              //   ElMessage({
              //     message: '暂无数据！',
              //     type: 'warning',
              //   })
              // } else {
              sessionStorage.setItem("arrall", JSON.stringify(res.result.result))
              //学生面板需要传递的参数
              let parameter = []
              parameter.push({
                SetAllResult: res.result.result,
                ChangePanel: 1,
                Panel: 'Student',
                Breadcrumbs: [
                  {
                    pathname: '实训任务',
                    path: '/SimulationTasks'
                  },
                  {
                    pathname: '成绩详情',
                    path: '/SimulationTasks'
                  }
                ]
              })
              console.log('parameter', parameter);

              ctx.emit("GetChangePanel", parameter)
              // }
            }   // ===============
          }
          console.log('zhixing到这里了');

        })
        .catch((error) => {

        });
    }
    //后端发送任务信息
    async function ProducLocalStorageSaveReques(Paramters) {
      let rep = await Application.PostMessageAsync(
        Opcode.SessionStorageSaveRequest,
        { Key: "Product", Value: Paramters }
      );
      if (rep.Success) {
        ProducOpen()
      }
    }
    //开始任务
    function StudentOpenTask(row, index) {
      console.log('row: ', row, 'index: ', index);
      let Token = sessionStorage.getItem("token")
      console.log('Token: ', Token);
      postData("/api/TrainingTask/GetTaskInfoById", JSON.stringify({ id: row.trainingTaskId }), sessionStorage.getItem("token")).
        then(function (res) {
          console.log('点击开始任务获取的res: ', res);
          if (res.result.success) {
            postData("/api/TaskManage/StartTask", JSON.stringify({ id: row.id }), sessionStorage.getItem("token")).
              then(function (rep) {
                if (rep.result.success) {
                  let ProductInventoryArr = JSON.parse(sessionStorage.getItem("ProductInventoryArr"))
                  console.log('ProductInventoryArr: ', ProductInventoryArr);
                  let id = sessionStorage.getItem("productId")
                  console.log('id: ', id);
                  let Paramters = {
                    Token: '',
                    ResultId: '',
                    FaultPointCollection: '',
                    UserName: '',
                    Duration: '',
                    Mode: '',
                    ProductType: '',
                    CarType: '',
                    SystemType: '',
                    ShortName: '',
                    // Player: 'VehicleDisassemblyAndAssembly.VR',
                    Player: '',
                    Task: res.result.result.taskModule,
                  }
                  let projectId = res.result.result.projectId.split(",")
                  let projectIdarr = []
                  for (let i = 0; i < projectId.length; i++) {
                    projectIdarr.push(parseInt(projectId[i]))
                  }
                  let FaultPointCollection = projectIdarr
                  let ResultId = row.trainingResultId
                  sessionStorage.setItem('ResultId', ResultId)
                  console.log('###################################', sessionStorage.getItem('ResultId'));
                  let UserName = sessionStorage.getItem("UserName")
                  let Duration = res.result.result.timeLong
                  for (let i = 0; i < ProductInventoryArr.length; i++) {
                    if (id.length == 2) {
                      if ("P100" + id === ProductInventoryArr[i].number) {
                        Paramters.ShortName = ProductInventoryArr[i].number
                        Paramters.ProductType = ProductInventoryArr[i].name
                        Paramters.CarType = ProductInventoryArr[i].vehicleModel
                        Paramters.SystemType = ProductInventoryArr[i].system
                        if (ProductInventoryArr[i].terminal === "PC") {
                          Paramters.Player = 'VehicleDisassemblyAndAssembly'
                        }
                        if (ProductInventoryArr[i].terminal === "VR") {
                          Paramters.Player = 'VehicleDisassemblyAndAssembly.VR'
                        }
                      }
                    } else if (id.length == 3) {
                      if ("P10" + id === ProductInventoryArr[i].number) {
                        Paramters.ShortName = ProductInventoryArr[i].number
                        Paramters.ProductType = ProductInventoryArr[i].name
                        Paramters.CarType = ProductInventoryArr[i].vehicleModel
                        Paramters.SystemType = ProductInventoryArr[i].system
                        if (ProductInventoryArr[i].terminal === "PC") {
                          Paramters.Player = 'VehicleDisassemblyAndAssembly'
                        }
                        if (ProductInventoryArr[i].terminal === "VR") {
                          Paramters.Player = 'VehicleDisassemblyAndAssembly.VR'
                        }
                      }
                    }

                  }

                  Paramters.Token = Token
                  Paramters.ResultId = ResultId
                  Paramters.FaultPointCollection = FaultPointCollection
                  Paramters.UserName = UserName
                  Paramters.Duration = Duration * 60
                  Paramters.Mode = parseInt(res.result.result.taskType)
                  ProducLocalStorageSaveReques(JSON.stringify(Paramters))
                }
              })
              .catch((error) => {

              });

          }
        })
        .catch((error) => {

        });


      // 添加用户id，产品id，学校id
      postData("/api/Quant/Create", JSON.stringify({ "CreatorId": sessionStorage.getItem("userid"), "ProductId": sessionStorage.getItem('productId'), "SchoolId": sessionStorage.getItem("schoolId") }), sessionStorage.getItem("token")).
        then(function (rep) {
          if (rep.success) {
            console.log('SchoolAuthority接口', rep);
          } else {
          }
        }).catch(error => {
          console.log('错误', error)
        });
    }
    //正式开启任务
    async function ProducOpen() {
      let id = sessionStorage.getItem("productId")
      let ProductInventoryArr = JSON.parse(sessionStorage.getItem("ProductInventoryArr"))
      let ShortName = ''
      let Type = ''
      let Launcher = ''
      let Executer = ''
      for (let i = 0; i < ProductInventoryArr.length; i++) {
        if (id.length == 2) {
          if ("P100" + id === ProductInventoryArr[i].number) {
            ShortName = ProductInventoryArr[i].number
            Type = parseInt(ProductInventoryArr[i].type)
            Launcher = ProductInventoryArr[i].launcher
            if (ProductInventoryArr[i].executer === null) {
              Executer = ''
            } else {
              Executer = ProductInventoryArr[i].executer
            }

          }
        } else if (id.length == 3) {
          if ("P10" + id === ProductInventoryArr[i].number) {
            ShortName = ProductInventoryArr[i].number
            Type = parseInt(ProductInventoryArr[i].type)
            Launcher = ProductInventoryArr[i].launcher
            if (ProductInventoryArr[i].executer === null) {
              Executer = ''
            } else {
              Executer = ProductInventoryArr[i].executer
            }

          }
        }
      }
      let rep = await Application.PostMessageAsync(Opcode.ProductLaunchRequest, { Type: Type, Id: id, ShortName: ShortName, DisplayName: "", Launcher: Launcher, Executer: Executer, Framerate: 60, Key: "Product" });
    }
    //分页执行的任务
    function handleSizeChange(size) {
      StudentTaskPage.pagesize = size
    }
    function handleCurrentChange(currentPage) {
      StudentTaskPage.currentPage = currentPage
    }
    function FNumToDate() {

    }
    return {
      State,
      StudentOpenTask,
      handleResult,
      dateFormats,
      StudentTaskPage,
      handleCurrentChange,
      handleSizeChange,
      Load,
      TimeChange,
    };
  },

});
</script>
<style lang="less" scoped>
.StudentTaskTable-Panel {
  position: absolute;
  width: 1360px;
  height: calc(100% - 290px);
  left: 520px;
  top: 280px;
  background: #ffffff;
  border-radius: 16px;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
}

.StudentTaskTable-Panel-title {
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.StudentTaskTable-Panel-title>div:nth-child(1) {
  margin-left: 16px;
  margin-top: 4px;
}

.StudentTaskTable-Panel-title>div:nth-child(1) img {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

.StudentTaskTable-Panel-title>div:nth-child(2) {
  margin-left: 10px;
  font-size: 18px;
  color: #81859c;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #81859c;
}

.StudentTaskTable-Panel-table {
  margin-left: 10px;
  width: 1340px;
  height: calc(100% - 60px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.StudentTaskTable-Panel-table .el-form-item {
  margin-bottom: 0px;
}

.StudentTaskTable-Panel-table .el-input__inner {
  text-align: center;
}

/deep/.StudentTaskTable-Panel-table .cell {
  text-align: center;
}

.StudentTaskTable-template-stare,
.StudentTaskTable-template-studentall,
.StudentTaskTable-template-Notinvolved,
.StudentTaskTable-template-Release {
  border-radius: 10px;
  border: 1px solid #e6e7ebff;
}

.StudentTaskTable-template-stare:hover {
  color: #ffffff;
  background: linear-gradient(90deg, #807de1, #218cde);
}

.StudentTaskTable-template-studentall:hover {
  color: #ffffff;
  background: linear-gradient(90deg, #807de1, #218cde);
}

.StudentTaskTable-template-Notinvolved:hover {
  color: #ffffff;
  background: linear-gradient(90deg, #807de1, #218cde);
}

.StudentTaskTable-template-Release:hover {
  color: #ffffff;
  background: linear-gradient(90deg, #807de1, #218cde);
}

/* 表格里面滚动条设置 */
.StudentTaskTable-Panel-table .el-table__body-wrapper::-webkit-scrollbar {
  width: 7px;
  background-color: #f5f5f5;
}

/* 表格里面滚动条设置 */
.StudentTaskTable-Panel-table .el-table__body-wrapper::-webkit-scrollbar-track {
  box-shadow: inset 0 0 2px rgba(230, 232, 236, 0.3);
  border-radius: 10px;
  background-color: #f5f5f5;
}

/* 表格里面滚动条设置 */
.StudentTaskTable-Panel-table .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 10px;
  box-shadow: inset 0 0 1.5px rgba(230, 232, 236, 0.2);
  background-color: rgba(230, 232, 236, 1);
}

.StudentTaskTable-el-pagination {
  margin-top: 15px;
}

/deep/.el-table th.el-table__cell>.cell {
  margin-left: 12px;
}

/deep/.el-table th.el-table__cell:last-child>.cell {
  margin-left: 0px;
}

// /deep/.column1 {
//   min-width: 250px;
// }

// /deep/.column3 {
//   min-width: 220px;
// }

// /deep/.column5 {
//   min-width: 350px;
// }</style>
